package com.kedacom.freedomLabel.view.activity.product;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;

import com.google.gson.Gson;
import com.kedacom.freedomLabel.Options;
import com.kedacom.freedomLabel.R;
import com.kedacom.freedomLabel.base.BaseActivity;
import com.kedacom.freedomLabel.databinding.ActivityProductProductControlBinding;
import com.kedacom.freedomLabel.model.DataControlResult;
import com.kedacom.freedomLabel.model.SelectType;
import com.kedacom.freedomLabel.model.bean.Category;
import com.kedacom.freedomLabel.model.bean.Operator;
import com.kedacom.freedomLabel.model.bean.Product;
import com.kedacom.freedomLabel.model.bean.Template;
import com.kedacom.freedomLabel.model.db.AppDatabase;
import com.kedacom.freedomLabel.model.db.dao.ProductDao;
import com.kedacom.freedomLabel.view.activity.SelectItemActivity;
import com.kedacom.freedomLabel.view.fragment.ListDataFragment;
import com.kedacom.freedomLabel.viewmodel.product.ProductControlViewModel;
import com.kedacom.lego.annotation.ContentView;
import com.kedacom.lego.annotation.OnMessage;
import com.kedacom.lego.annotation.ViewModel;
import com.kedacom.lego.fast.validation.RegexTemplate;
import com.kedacom.lego.message.LegoMessageManager;

import java.util.regex.Pattern;


@ContentView(R.layout.activity_product_product_control)
@ViewModel(ProductControlViewModel.class)
public class ProductControlActivity extends BaseActivity<ActivityProductProductControlBinding, ProductControlViewModel> {

    Product mSelectedItem;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        closeEditLayout();
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        ProductDao productDao = AppDatabase.getInstance().productDao();
        ListDataFragment<Product> fragment = ListDataFragment.newInstance(productDao);
        transaction.add(mBinding.recyclerContainer.getId(), fragment);
        transaction.commit();
        mBinding.boxGroup.setOnClickListener(v -> {
            boolean checked = mBinding.boxGroup.isChecked();
            if (checked) {
                if (mViewModel.tvGroupText.getValue() == null) {
                    Intent intent = new Intent(ProductControlActivity.this, SelectItemActivity.class);
                    intent.putExtra(Options.KEY_SELECT_TYPE, SelectType.TYPE_CATEGORY);
                    startActivityForResult(intent, 0x11);
                }
                mBinding.tvGroup.setEnabled(true);
            } else {
                mViewModel.tvGroupText.set(null);
                mBinding.tvGroup.setTag(null);
                mBinding.boxGroup.setTag(null);
                mBinding.tvGroup.setEnabled(false);
            }
        });

        mBinding.tvGroup.setOnClickListener(v -> {
            Intent intent = new Intent(ProductControlActivity.this, SelectItemActivity.class);
            intent.putExtra(Options.KEY_SELECT_TYPE, SelectType.TYPE_CATEGORY);
            startActivityForResult(intent, 0x11);
        });

        mBinding.ivGroupClear.setOnClickListener(v -> {
            if (mViewModel.tvGroupText.getValue() != null) {
                showDialog("确认删除已选择的分组信息", getString(R.string.dialog_okbtn_text), (dialog, which) -> {
                    dialog.dismiss();
                    mViewModel.boxGroupChecked.set(false);
                    mBinding.tvGroup.setEnabled(false);
                    mViewModel.tvGroupText.set(null);
                    mBinding.tvGroup.setTag(null);
                    mBinding.boxGroup.setTag(null);
                });
            }
        });
        mBinding.ivLabelClear.setOnClickListener(v -> {
            if (mViewModel.tvLabelText.getValue() != null) {
                showDialog("确认删除已选择的标签模板", getString(R.string.dialog_okbtn_text), (dialog, which) -> {
                    dialog.dismiss();
                    mViewModel.tvLabelText.set(null);
                    mBinding.tvLabel.setTag(null);
                });
            }
        });
        mBinding.tvLabel.setOnClickListener(v -> {
            Intent intent = new Intent(ProductControlActivity.this, SelectItemActivity.class);
            intent.putExtra(Options.KEY_SELECT_TYPE, SelectType.TYPE_LABEL);
            startActivityForResult(intent, 0x11);
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x11 && resultCode == RESULT_OK) {
            String jsonData = data.getStringExtra(Options.KEY_SELECT_RESULT);
            SelectType dataType = (SelectType) data.getSerializableExtra(Options.KEY_SELECT_TYPE);
            if (dataType == null || TextUtils.isEmpty(jsonData)) return;
            Gson gson = new Gson();
            if (dataType == SelectType.TYPE_CATEGORY) {
                Category category = gson.fromJson(jsonData, Category.class);
                mViewModel.tvGroupText.set(category.name);
                mBinding.tvGroup.setTag(category.uuid);
                mBinding.boxGroup.setTag(category.number);
                mViewModel.boxGroupChecked.set(true);
            } else if (dataType == SelectType.TYPE_LABEL) {
                Template template = gson.fromJson(jsonData, Template.class);
                mViewModel.tvLabelText.set(template.type);
                mBinding.tvLabel.setTag(template.type);
            }
        }
    }

    /**
     * 接收数据选择
     *
     * @param item 选择的Item
     */
    @OnMessage(value = Options.MSG_SELECT_ITEM, discard = true)
    public void receiveItemClickMessage(Product item) {
        closeEditLayout();
        mSelectedItem = item;
        mViewModel.evNameText.set(item.name);
        mViewModel.evNumberText.set(item.number);
        mViewModel.evSingleWeightText.set(item.singleWeight == null ? "" : String.valueOf(item.singleWeight));
        mViewModel.evPreTareText.set(item.preTare == null ? "" : String.valueOf(item.preTare));
        mViewModel.evTopText.set(item.topLimit == null ? "" : String.valueOf(item.topLimit));
        mViewModel.evLowText.set(item.lowLimit == null ? "" : String.valueOf(item.lowLimit));
        mViewModel.boxGroupChecked.set(item.openGroupSetting);
        mViewModel.tvIdChecked.set(item.openPreIDSetting);
        mViewModel.tvGroupText.set(item.groupName);
        mViewModel.tvLabelText.set(item.label);
        mBinding.tvGroup.setTag(item.groupUUID);
        mBinding.boxGroup.setTag(item.groupNumber);
        mBinding.tvLabel.setTag(item.label);
    }

    /**
     * 接收数据更新结果通知
     *
     * @param result 结果
     */
    @OnMessage(value = Options.MSG_SAVE_ITEM_RESULT, discard = true)
    public void receiveDataSaveResult(DataControlResult<Product> result) {
        if (result.result) {
            closeEditLayout();
            mSelectedItem = result.data;
        }
    }

    /**
     * 接收数据删除结果通知
     *
     * @param result 结果
     */
    @OnMessage(value = Options.MSG_DELETE_ITEM_RESULT, discard = true)
    public void receiveDataDeleteResult(DataControlResult<Product> result) {
        if (result.result) {
            mSelectedItem = null;
            closeEditLayout();
            clear();
        }
    }

    /**
     * 接收新增数据结果通知
     *
     * @param result 结果
     */
    @OnMessage(value = Options.MSG_ADD_ITEM_RESULT, discard = true)
    public void addItemComplete(DataControlResult<Product> result) {
        if (result.result) {
            closeEditLayout();
        }
    }

    @OnMessage(value = Options.MSG_RECOVERY_ITEM_DETAIL, discard = true)
    public void recoveryDetailLayout() {
        mBinding.save.setTag(null);
        clear();
        closeEditLayout();
    }

    // 保存
    public void onSaveIDViewClick(View view) {
        beep();
        String name = mBinding.evName.getText().toString();
        String number = mBinding.evNumber.getText().toString();
        if (!Pattern.compile(RegexTemplate.NOT_EMPTY).matcher(name).matches()) {
            showToast(getString(R.string.validation_empty_name), TOAST_WARNING);
            return;
        }
        if (!Pattern.compile(RegexTemplate.NOT_EMPTY).matcher(number).matches()) {
            showToast(getString(R.string.validation_empty_number), TOAST_WARNING);
            return;
        }
        Object tag = mBinding.save.getTag();
        if (tag != null) {
            mSelectedItem.groupUUID = mBinding.tvGroup.getTag() == null ? null : mBinding.tvGroup.getTag().toString();
            mSelectedItem.label = mBinding.tvLabel.getTag() == null ? null : mBinding.tvLabel.getTag().toString();
            mViewModel.updateID(mSelectedItem);
        } else {
            String groupTag = mBinding.tvGroup.getTag() == null ? null : mBinding.tvGroup.getTag().toString();
            String groupNumber = mBinding.boxGroup.getTag() == null ? null : mBinding.boxGroup.getTag().toString();
            String labelTag = mBinding.tvLabel.getTag() == null ? null : mBinding.tvLabel.getTag().toString();
            mViewModel.saveID(groupTag, labelTag,groupNumber);
        }
    }

    @OnMessage(value = Options.MSG_ADD_EXISTS_RESULT, discard = true)
    public void exitItemComplete(DataControlResult<Product> result) {
        if (result.result) {
            showToast(getString(R.string.alraad_product_name)+"该产品名称："+result.data.name, TOAST_WARNING);
//            closeEditLayout();
        }
    }

    // 删除
    public void onDeleteIDViewClick(View view) {
        beep();
        showDialog("是否删除", "删除", (dialog, which) -> {
            LegoMessageManager.getInstance().sendEmptyMessage(Options.MSG_DELETE_ITEM);
            dialog.dismiss();
        });
    }

    // 增加
    public void onAddIDViewClick(View view) {
        beep();
        openEditLayout();
        // 标识新增
        mBinding.save.setTag(null);
        clear();
    }

    // 编辑
    public void onEditIDViewClick(View view) {
        beep();
        if (mSelectedItem != null) {
            openEditLayout();
            // 标识编辑
            mBinding.save.setTag(mSelectedItem.uuid);
        }
    }

    // 清除
    public void onClearIDViewClick(View view) {
        beep();
        clear();
    }

    // 取消
    public void onCancelIDViewClick(View view) {
        beep();
        closeEditLayout();
        // 标识新增
        mBinding.save.setTag(null);
    }

    // 退出
    public void onBackClick(View view) {
        beep();
        finish();
    }

    private void clear() {
        mBinding.save.setTag(null);
        mViewModel.boxGroupChecked.set(false);
        mViewModel.tvIdChecked.set(false);
        mViewModel.evNameText.set(null);
        mViewModel.evNumberText.set(null);
        mViewModel.evSingleWeightText.set(null);
        mViewModel.evPreTareText.set(null);
        mViewModel.evTopText.set(null);
        mViewModel.evLowText.set(null);
        mViewModel.tvGroupText.set(null);
        mViewModel.tvLabelText.set(null);
    }

    private void closeEditLayout() {
        mBinding.ivLabelClear.setEnabled(false);
        mBinding.ivGroupClear.setEnabled(false);
        mBinding.tvGroup.setEnabled(false);
        mBinding.tvLabel.setEnabled(false);
        mBinding.boxGroup.setEnabled(false);
        mBinding.boxId.setEnabled(false);
        mBinding.evName.setEnabled(false);
        mBinding.evNumber.setEnabled(false);
        mBinding.evSingleWeight.setEnabled(false);
        mBinding.evPreTare.setEnabled(false);
        mBinding.evTop.setEnabled(false);
        mBinding.evLow.setEnabled(false);
        mBinding.controlAddLayout.setVisibility(View.VISIBLE);
        mBinding.controlSaveLayout.setVisibility(View.GONE);
    }

    private void openEditLayout() {
        mBinding.ivLabelClear.setEnabled(true);
        mBinding.ivGroupClear.setEnabled(true);
        mBinding.tvGroup.setEnabled(true);
        mBinding.tvLabel.setEnabled(true);
        mBinding.boxGroup.setEnabled(true);
        mBinding.boxId.setEnabled(true);
        mBinding.evName.setEnabled(true);
        mBinding.evNumber.setEnabled(true);
        mBinding.evSingleWeight.setEnabled(true);
        mBinding.evPreTare.setEnabled(true);
        mBinding.evTop.setEnabled(true);
        mBinding.evLow.setEnabled(true);
        mBinding.controlAddLayout.setVisibility(View.GONE);
        mBinding.controlSaveLayout.setVisibility(View.VISIBLE);
    }
}